package com.qf.vote2203.dbvote.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@Component
//@ServerEndpoint("/vote/{id}")
public class PushStaticWebSocketServer {

    public static ConcurrentHashMap<String,Session> map
            = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session){
        map.put(id,session);
    }


    @OnClose
    public void onClose(@PathParam("id") String id){
        map.remove(id);
    }


    public static void sendMsg(String msg) throws IOException {

        // 给所有的 websocket链接推送 消息
        for (Map.Entry<String, Session> entry : map.entrySet()) {

            final Session session = entry.getValue();

            session.getBasicRemote().sendText(msg);

        }

    }

}
